package com.chookss.home.document;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.knowledge.adaper.MyDirectoryAdapter;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class DocumentHomeFragment extends SimpleImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;

    @BindView(R.id.rcvDirectory)
    RecyclerView rcvDirectory;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;

    private MyDirectoryAdapter directoryAdapter;

    private List<KnowledgeEntity> directoryList = new ArrayList<>();

    public DocumentHomeFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_document_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        //注册接受
        EventBus.getDefault().register(this);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        rcvDirectory.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rcvDirectory.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)));
        directoryAdapter = new MyDirectoryAdapter(R.layout.item_video_database_directory, mContext, directoryList, 2,"");
        rcvDirectory.setAdapter(directoryAdapter);
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                getCatalogData();
            }
        });
        srlView.autoRefresh();
        srlView.setEnableLoadMore(false);//是否启用加载功能
    }

    private void getCatalogData() {
        Map<String, String> map = new HashMap<>();

//        resourceType  资源类型（1资料，2长视频，3短视频 6图片）
//        catalogType 目录类型 1-小视频，2长视频 3资料库
        map.put("resourceType", "1");
        map.put("catalogType", "3");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<KnowledgeEntity>>>() {
        }.getType(), null, Urls.selectAPPCatalogTreeGlobal, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<KnowledgeEntity>>() {
            @Override
            public void onSuccess(List<KnowledgeEntity> data) {
                loadEnd();
                if (data != null && data.size() > 0) {
                    directoryList.clear();
                    directoryList.addAll(data);
                    directoryAdapter.notifyDataSetChanged();
                }
                if (directoryList.size() == 0) {
                    llNone.setVisibility(View.VISIBLE);
                    rcvDirectory.setVisibility(View.GONE);
                } else {
                    llNone.setVisibility(View.GONE);
                    rcvDirectory.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if(!Utils.isNull(msg)){
                if(msg.equals("RefreshDirectory")){
                    KLog.i("=====");
                    srlView.autoRefresh();
                }
            }
        }
    }
    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }
}
